package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.util.StringUtil;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;

@Service
@Slf4j
public class WechatServiceImpl implements WechatService {
    private static final String GET_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    @Value("${wechat.appId}")
    private String appid;
    @Value("${wechat.appSecret}")
    private String secret;
    /**
     * 获取微信用户的 openid
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        //封装请求
        String result = HttpRequest.get(GET_OPENID_URL)
                .form("appid",appid)
                .form("secret",secret)
                .form("js_code",code)
                .form("grant_type","authorization_code")
                .timeout(5000)
                .execute()
                .body();
        //使用hutool将result转换成JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(result);
        log.info("获取openid的结果 = " + jsonObject);
        //使用hutool获取openid
        String openid = jsonObject.getStr("openid");
        //做非空判断，若为空，则抛出异常
        if(StringUtil.isEmpty(openid)){
            throw new ServiceException("获取openid失败，请检查后重试");
        }
        return openid;
    }

    /**
     * 获取微信用户的手机号码
     *
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhoneNumber(String phoneCode) {
        String url = GET_PHONE_URL + testGetAccessToken();
        Map<String, String> map = Collections.singletonMap("code", phoneCode);
        String result = HttpRequest.post(url)
                .body(JSONUtil.toJsonStr(map))
                .timeout(5000)
                .execute().body();
        log.info("获取手机号码的结果 = " + result);
        JSONObject jsonObject = JSONUtil.parseObj(result);

        String phone = jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        if(StringUtil.isEmpty(phone)){
            throw new ServiceException("获取手机号码失败，请检查后重试");
        }
        return phone;
    }
    /**
     * 获取微信授权，获取access_token 有效去为2小时
     * @return
     */

    private String testGetAccessToken() {
        String url = ACCESS_TOKEN_URL;
        String body = HttpRequest.get(url)
                .form("grant_type","client_credential")
                .form("appid",appid)
                .form("secret", secret)
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        log.info("获取微信授权：{} ", jsonObject);
        String accessToken = jsonObject.getStr("access_token");
        return accessToken;
    }
}
